import React  from 'react';
import {message,Icon,Button,Input,Row,Col,Card,Anchor,Table,Dropdown,Menu,Form,DatePicker,InputNumber,Upload,Select} from 'antd';
import styles from '../style/PropertyDataDetailInfo.scss';
import api from 'container/api';
import moment from 'moment';
const Option = Select.Option;
const { RangePicker } = DatePicker;

import {
  ASSET_LEVEL,
  IS_NOT,
  GUARANTEE,
  TRANSPORT_TYPE,
  RETURNED_MONEY_WAY,
  RETURNED_MONEY_SOURCE,
  REMARK_TYPE,
  IS_NOT_MAP
} from 'constants/index';

//基础信息
class BaseInfo extends React.Component {

  constructor(props){
    super(props);
    let {id} = props;
    this.state ={
      id,
      data:{},
      isEdit:false
    }
  }

  componentWillMount(){
    this.doFetch();
  }

  async doFetch(){
    let {id} = this.state;
    let result = await api('/assets/basic-info',{id});
    if(!result.success){
      message.error(result.message);
      return
    }
    let data = result.data;
    Object.keys(data).forEach((key,index) => {
      if(key.endsWith('files') && Array.isArray(data[key])){
        data[key].forEach((item,index) => {
          item.uid = this.uuid();
        })
      }
    })
    this.setState({data:result.data,isEdit:false});
  }

  toggleEdit (isEdit){
    let {data} = this.state;
    this.setState({isEdit})
  }

  handleSave = () => {
    this.props.form.validateFields((err, values) => {
      if (err) return;
      this.save({...values})
    });
  }

  async save (values) {
    values.asset_id = this.state.id;
    values.id = this.state.data.id;
    let result = await api("/assets/basic-info/edit",values);
    if(!result.success){
      message.error(result.message);
      return
    }
    message.success("更新基础信息成功" , 1 ,() => {
      this.doFetch();
    })
  }

  uuid(){
    return Math.random().toString(36).slice(2);
  }

  render(){
    let {data,isEdit} = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <Card 
        title="基础信息" 
        bordered={false} 
        bodyStyle={{backgroundColor:'#fff',padding:'0'}}
        extra={
          this.renderTd(
            <div>
              <Button style={{marginRight:5}} onClick={this.toggleEdit.bind(this,false)}>取消</Button>
              <Button type='primary' onClick={this.handleSave}>保存</Button>
            </div>,
            <a href='javascript:void 0' onClick={this.toggleEdit.bind(this,true)}>
            <Icon type="edit" />
            </a>
          )
        }
      >
        <table className={styles.table}>
          <tbody  className='table-form'>
            <tr>
              <th>资产总金额</th>
              <td>
                {data.money_sum}元
              </td>
              <th>剩余资产金额</th>
              <td>
                {data.money_left}元
              </td>
            </tr>
            <tr>
              <th>应收起始日</th>
              <td>
                {data.start_date}
              </td>
              <th>预计收款日</th>
              <td>
                {data.predict_date}
              </td>
            </tr>
            <tr>
              <th>应收账款分级</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('level', {
                      rules: [{required: true, message: '请选择应收账款分级' }],
                      initialValue:data.level
                    })(
                      <Select>
                        {Object.keys(ASSET_LEVEL).map((key,index) => {
                          return (<Option key={index} value={key}>{ASSET_LEVEL[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  ASSET_LEVEL[data.level]
                )}
              </td>
              <th>逾期天数</th>
              <td>
                {data.expire_days}天
              </td>
            </tr>
            <tr>
              <th>是否结算</th>
              <td>
                {IS_NOT(data.balanced)}
              </td>
              <th>结算金额</th>
              <td>
                {data.money_balanced}元
              </td>
            </tr>
            <tr>
              <th>是否有保险</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('insured', {
                      rules: [{required: true, message: '请选择是否有保险' }],
                      initialValue:data.insured==true?'1':'0'
                    })(
                      <Select>
                        {Object.keys(IS_NOT_MAP).map((key,index) => {
                          return (<Option key={index} value={key} >{IS_NOT_MAP[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  `${IS_NOT(data.insured)}`
                )}
              </td>
              <th>保险覆盖率</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('insurance_coverage', {
                      rules: [{required: false, message: '请输入保险覆盖率' }],
                      initialValue:data.insurance_coverage
                    })(
                      <Input addonAfter='%' />
                    )}
                  </Form.Item>,
                  `${data.insurance_coverage}%`
                )}
              </td>
            </tr>
            <tr>
              <th>保险单</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('insurance_files', {
                    rules: [{ required: false, message: '请上传保险单' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.insurance_files
                  })(
                    <Upload {...this.uploadProps(8,'insurance_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
            <tr>
              <th>担保方式</th>
              <td colSpan={3}>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('guarantee', {
                      rules: [{required: true, message: '请选择担保方式' }],
                      initialValue:data.guarantee
                    })(
                      <Select style={{width:200}}>
                        {Object.keys(GUARANTEE).map((key,index) => {
                          return (<Option key={index} value={key} >{GUARANTEE[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  GUARANTEE[data.guarantee]
                )}
              </td>
            </tr>
            <tr>
              <th>担保文件</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('guarantee_files', {
                    rules: [{ required: false, message: '请上传担保文件' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.guarantee_files
                  })(
                    <Upload {...this.uploadProps(9,'guarantee_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
            <tr>
              <th>是否有质保金</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('deposited', {
                      rules: [{required: true, message: '请选择是否有保险' }],
                      initialValue:data.deposited==true?'1':'0'
                    })(
                      <Select>
                        {Object.keys(IS_NOT_MAP).map((key,index) => {
                          return (<Option key={index} value={key} >{IS_NOT_MAP[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  IS_NOT(data.deposited)
                )}
              </td>
              <th>质保金金额</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('money_deposited', {
                      rules: [{required: true, message: '请输入质保金金额' }],
                      initialValue:data.money_deposited
                    })(
                      <Input addonAfter='元' />
                    )}
                  </Form.Item>,
                  `${data.money_deposited}元`
                )}
              </td>
            </tr>
            <tr>
              <th>质保文件</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('deposited_files', {
                    rules: [{ required: false, message: '请上传质保文件' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.deposited_files
                  })(
                    <Upload {...this.uploadProps(10,'deposited_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
            <tr>
              <th>是否有展期条款</th>
              <td colSpan={3}>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('expanded', {
                      rules: [{required: true, message: '请选择是否有展期条款' }],
                      initialValue:data.expanded==true?'1':'0'
                    })(
                      <Select>
                        {Object.keys(IS_NOT_MAP).map((key,index) => {
                          return (<Option key={index} value={key} >{IS_NOT_MAP[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  IS_NOT(data.expanded)
                )}
              </td>
            </tr>
            <tr>
              <th>展期条款文件</th>
              <td colSpan={3}>
                {getFieldDecorator('expanded_files', {
                    rules: [{ required: false, message: '请上传展期条款文件' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.expanded_files
                  })(
                    <Upload {...this.uploadProps(11,'expanded_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
              </td>
            </tr>
          </tbody>
        </table>
      </Card>
    )
  }
  uploadProps = (file_type,field) => {
    let _this = this;
    let {data} = this.state;
    data[field] = data[field] || [];
    return {
      customRequest:async ({ file, fileList }) => {
        let {defaultFileList=[]} = this.state;
        let result = await api.upload(`/file/upload?file_type=${file_type}`,file);
        if(result){
          let uid = this.uuid();
          data[field].push({
            name:file.name,
            url:result.data.url,
            type:result.data.type,
            uid:uid,
            status:'done'
          })
        }
        this.props.form.setFieldsValue({
          [field]:data[field]
        })
        this.setState({data})
      },
      onRemove:(file) => {
        let {isEdit} = _this.state;
        return isEdit
      }
    }
  }
  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }
  renderTd (editHtml,html) {
    let {isEdit} = this.state;
    if(isEdit) return editHtml;
    return html;
  }
}
export default Form.create()(BaseInfo);
